package com.shareach.http.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.shareach.common.CollectionNames;
import com.shareach.dao.mongo.impl.BaseShopDaoImpl;
import com.shareach.dao.mongo.impl.BizActivityDaoImpl;
import com.shareach.dao.mongo.impl.BizActivityShopDaoImpl;
import com.shareach.dao.mongo.impl.BizCardDaoImpl;
import com.shareach.dao.mongo.impl.BizTicketDaoImpl;
import com.shareach.dao.mongo.impl.BizTuanShopDaoImpl;
import com.shareach.dao.redis.impl.DeployRDao;
import com.shareach.dao.redis.impl.DeployRDao.DeployType;
import com.shareach.dao.redis.impl.MatchRDao;
import com.shareach.dao.redis.impl.SnatchRDao;
import com.shareach.domain.BaseShopDomain;
import com.shareach.domain.BizActivityDomain;
import com.shareach.domain.BizActivityShopDomain;
import com.shareach.domain.BizCardDomain;
import com.shareach.domain.BizTicketDomain;
import com.shareach.domain.BizTuanShopDomain;
import com.shareach.domain.DiscountType;
import com.shareach.redis.NewJedis;
import com.shareach.redis.RedisService;
import com.shareach.service.BizCardService;
import com.shareach.web.basic.Answer;
import com.shareach.web.controller.BaseController;

@Controller
@RequestMapping("/tool")
public class ToolController extends BaseController {
	@Autowired
	private RedisService redisService;
	@Autowired
	private MatchRDao matchRDao;
	@Autowired
	private DeployRDao deployRDao;
	@Autowired
	private SnatchRDao snaRDao;
	@Autowired
	private BizTuanShopDaoImpl tuanShopDao;
	@Autowired
	private BizCardDaoImpl cardDao;
	@Autowired
	private BizActivityShopDaoImpl activityShopDao;
	@Autowired
	private BizActivityDaoImpl activityDao;
	@Autowired
	private BizTicketDaoImpl ticketDao;
	@Autowired
	private BaseShopDaoImpl shopDao;
	@Autowired
	private BizCardService cardService;
	@Autowired
	private DeployUtils deployUtils;

	@RequestMapping(value = "/index.htm")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("admin/tool/index");
		return mav;
	}
	
	/**
	 * 清理重复卡惠数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/clearDuplicateCard.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> clearDuplicateCard(HttpServletRequest request, HttpServletResponse response) {
		// ====卡惠================================================================================
		List<BizCardDomain> cardList = cardService.getList(new BizCardDomain());

		Map<String, String> objMap = new HashMap<String, String>();
		Map<String, String> duplicateMap = new HashMap<String, String>();

		for (BizCardDomain card : cardList) {
			String site = card.getSite();
			String siteId = card.getSiteId();
			String key = siteId + "-" + site;
			String value = String.valueOf(card.getId());
			// remove if title is null
			if (StringUtils.isEmpty(card.getTitle())) {
				removeCard(card.getId(), site, siteId);
			}
			if (objMap.containsKey(key)) {
				removeCard(card.getId(), site, siteId);
				duplicateMap.put(key, objMap.get(key));
			} else {
				objMap.put(key, value);
			}
		}
		if (duplicateMap.size() > 0) {
			for (Entry<String, String> entry : duplicateMap.entrySet()) {
				String[] sites = entry.getKey().split("-");
				String site = sites[1];
				String siteId = sites[0];
				removeCard(Long.valueOf(entry.getValue()), site, siteId);
			}
		}
		return createAnswer();
	}

	/**
	 * 删除卡惠数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/cleanActivity.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> cleanActivity(HttpServletRequest request, HttpServletResponse response) {
		//TODO ypx先删除生产库数据 ，1.mongo中shop的对应count置为0；2.删除对应mysql数据
		// ====删除活动================================================================================
		//删除mongo数据
		activityShopDao.delete(new Query(), BizActivityShopDomain.class);
		activityDao.delete(new Query(), BizActivityDomain.class);
		//清除计数器
		activityShopDao.zeroCounter(CollectionNames.BIZACTIVITYSHOP);
		activityDao.zeroCounter(CollectionNames.BIZACTIVITY);
		// 移除Delpoy的所有的Key
		removeDeployRedis(DeployType.Activity);
		removeDeployRedis(DeployType.ActivityShop);
		removeMatchRedis(DiscountType.Activity);
		return createAnswer();
	}

	/**
	 * 将匹配过，但是未匹配上的优惠商户重新匹配
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/unmapRematch.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> rematchUmmap(HttpServletRequest request, HttpServletResponse response) {
		matchRDao.setRemap(DiscountType.Activity);
		matchRDao.setRemap(DiscountType.Card);
		matchRDao.setRemap(DiscountType.Ticket);
		matchRDao.setRemap(DiscountType.Tuan);
		return createAnswer();
	}
	
	
	/**
	 * 取消匹配，同时清空delploy
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/unmapTuan.htm", method = RequestMethod.POST)
	public @ResponseBody
	Answer<?> unmapTuan(HttpServletRequest request, HttpServletResponse response) {
		// ====团购================================================================================
		long idMax = 0L;
		List<BizTuanShopDomain> tuanShopList = tuanShopDao.findList(createQuery(idMax));
		while (tuanShopList != null && !tuanShopList.isEmpty()) {
			for (BizTuanShopDomain tuanShop : tuanShopList) {
				// 将此优惠商户重新放到未匹配队列中
				matchRDao.resetDiscountUnmap(DiscountType.Tuan, tuanShop.getId());
				idMax = tuanShop.getId();
			}
			tuanShopList = tuanShopDao.findList(createQuery(idMax));
		}
		// 清空ShopId
		tuanShopDao.unset(BizTuanShopDomain.class, "shopId", "deployTime", "creatTime", "matchTime");

		// 移除Delpoy的所有的Key
		removeDeployRedis(DeployType.Tuan);
		removeDeployRedis(DeployType.TuanShop);

		return createAnswer();
	}

	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/unmapAct.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unmapActivity(HttpServletRequest request, HttpServletResponse response) {
		// ====活动================================================================================
		long idMax = 0L;
		List<BizActivityShopDomain> activityShopList = activityShopDao.findList(createQuery(idMax));
		while (activityShopList != null && !activityShopList.isEmpty()) {
			for (BizActivityShopDomain activityShop : activityShopList) {
				// 将此优惠商户重新放到未匹配队列中
				matchRDao.resetDiscountUnmap(DiscountType.Activity, activityShop.getId());
				idMax = activityShop.getId();
			}
			activityShopList = activityShopDao.findList(createQuery(idMax));
		}
		// 清空ShopId
		activityShopDao.unset(BizActivityShopDomain.class, "shopId", "deployTime", "creatTime", "matchTime");

		// 移除Delpoy的所有的Key
		removeDeployRedis(DeployType.Activity);
		removeDeployRedis(DeployType.ActivityShop);
		return createAnswer();
	}

	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/unmapCard.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unmapCard(HttpServletRequest request, HttpServletResponse response) {
		// ====卡================================================================================
		long idMax = 0L;
		List<BizCardDomain> cardList = cardDao.findList(createQuery(idMax));
		while (cardList != null && !cardList.isEmpty()) {
			for (BizCardDomain card : cardList) {
				// 将此优惠商户重新放到未匹配队列中
				matchRDao.resetDiscountUnmap(DiscountType.Card, card.getId());
				idMax = card.getId();
			}
			cardList = cardDao.findList(createQuery(idMax));
		}
		// 清空ShopId
		cardDao.unset(BizCardDomain.class, "shopId", "deployTime", "creatTime", "matchTime");

		// 移除Delpoy的所有的Key
		removeDeployRedis(DeployType.Card);

		return createAnswer();
	}
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/unmapTicket.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unmapTicket(HttpServletRequest request, HttpServletResponse response) {
		// ====卡================================================================================
		long idMax = 0L;
		List<BizTicketDomain> ticketList = ticketDao.findList(createQuery(idMax));
		while (ticketList != null && !ticketList.isEmpty()) {
			for (BizTicketDomain ticket : ticketList) {
				// 将此优惠商户重新放到未匹配队列中
				matchRDao.resetDiscountUnmap(DiscountType.Ticket, ticket.getId());
				idMax = ticket.getId();
			}
			ticketList = ticketDao.findList(createQuery(idMax));
		}
		// 清空ShopId
		ticketDao.unset(BizTicketDomain.class, "shopId", "deployTime", "creatTime", "matchTime");

		// 移除Delpoy的所有的Key
		removeDeployRedis(DeployType.Ticket);

		return createAnswer();
	}
	
	/**
	 * 删除匹配的微博Id
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/unmapSina.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unmapSina(HttpServletRequest request, HttpServletResponse response) {
		long idMax = 0L;
		List<BaseShopDomain> shopList = shopDao.findList(createQuery(idMax));
		while (shopList != null && !shopList.isEmpty()) {
			for (BaseShopDomain shop : shopList) {
				// 将此优惠商户重新放到未匹配队列中
				matchRDao.resetDiscountUnmap(DiscountType.Weibo, shop.getId());
				idMax = shop.getId();
			}
			shopList = shopDao.findList(createQuery(idMax));
		}
		// 清空Shop中的微博字段
		shopDao.unset(BaseShopDomain.class, "weiboId", "weiboIds");
		return createAnswer();
	}
	
	/**
	 * 重新采集新浪微博的数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/resnatchSinaTipPhoto.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> resnatchSinaTipPhotoes(HttpServletRequest request, HttpServletResponse response) {
		long idMax = 0L;
		List<BaseShopDomain> shopList = shopDao.findList(createWeiboQuery(idMax));
		while (shopList != null && !shopList.isEmpty()) {
			for (BaseShopDomain shop : shopList) {
				// 将此优惠商户重新放到未匹配队列中
				deployRDao.addDeploy(shop.getWeiboId());
				if(shop.getWeiboIds()!=null){
					for(String weiboId:shop.getWeiboIds()){
						deployRDao.addDeploy(weiboId);
					}
				}
				idMax = shop.getId();
			}
			shopList = shopDao.findList(createQuery(idMax));
		}
		return createAnswer();
	}
	/**
	 * 将商户放入微博匹配队列
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/addToSinaTipPhotoQue.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> addShopToWeiboQue(HttpServletRequest request, HttpServletResponse response) {
		long idMax = 0L;
		List<BaseShopDomain> shopList = shopDao.findList(createQuery(idMax));
		while (shopList != null && !shopList.isEmpty()) {
			for (BaseShopDomain shop : shopList) {
				// 将此优惠商户重新放到未匹配队列中
				matchRDao.addDiscountUnmap(DiscountType.Weibo, shop.getId());
				idMax = shop.getId();
			}
			shopList = shopDao.findList(createQuery(idMax));
		}
		return createAnswer();
	}
	
	private Query createWeiboQuery(long idMax){
		Query query = this.createQuery(idMax);
		query.addCriteria(new Criteria().orOperator(
				Criteria.where("weiboId").ne(null),
				Criteria.where("weiboIds").ne(null)
				));
		return query;
	}


	@RequestMapping(value = "/unmapShop.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unmapShop(HttpServletRequest request, HttpServletResponse response) {
		// 团购
		unmapTuan(request, response);
		// 活动
		unmapActivity(request, response);
		// 普惠
		unmapCard(request, response);
		// 清空商户
		shopDao.remove(null, BaseShopDomain.class);
		// 更新计数器为0
		shopDao.zeroCounter(CollectionNames.BASESHOP);
		// 移除Delpoy的所有的Key
		removeDeployRedis(DeployType.Shop);
		return createAnswer();
	}

	private Answer<?> createAnswer() {
		Answer<String> answer = new Answer<String>();
		answer.setCode(0);
		answer.setMsg("ok");
		return answer;
	}

	private void removeDeployRedis(DeployType type) {
		NewJedis redis = redisService.getJedis();
		redis.del(String.format("dep:%s:que", type.getCode()));
		redis.del(String.format("dep:%s:time", type.getCode()));
		redis.del(String.format("dep:%s:err", type.getCode()));
	}

	/**
	 * 清理redis match队列，只有在删除业务数据库才对应删除该队列
	 * 
	 * @param type
	 */
	private void removeMatchRedis(DiscountType type) {
		NewJedis redis = redisService.getJedis();
		redis.del(String.format("match:un:%s", type.getCode()));
		redis.del(String.format("match:suc:%s", type.getCode()));
	}

	private Query createQuery(Long idMax) {
		Query query = new Query();
		query.addCriteria(Criteria.where("_id").gt(idMax));
		query.sort().on("_id", Order.ASCENDING);
		query.limit(100);
		return query;
	}

	/**
	 * 根据id删除
	 * 
	 * @param card
	 * @param site
	 * @param siteId
	 */
	private void removeCard(Long cardId, String site, String siteId) {
		BizCardDomain qu = new BizCardDomain();
		qu.setId(cardId);
		// del mongo
		cardService.del(qu);
		// del redis snatch
		snaRDao.removeRedis(site, siteId);
		// del redis match
		matchRDao.removeRedis(DiscountType.Card, siteId);
	}


	@RequestMapping(value = "/undepTuan.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unDeployTuan(HttpServletRequest request, HttpServletResponse response) {
		Answer<?> result = createAnswer();
		try{
			NewJedis redis = redisService.getJedis();
			//团购商户
			redisKeys(redis, DeployType.TuanShop);
			//团购
			redisKeys(redis, DeployType.Tuan);
		}catch(Exception exp){
			result.setCode(-1);
			result.setMsg(exp.getMessage());
			log.error(exp.getMessage(),exp);
		}
		return result;
	}
	@RequestMapping(value = "/undepAndClearTuan.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unDeployAndClearTuan(HttpServletRequest request, HttpServletResponse response) {
		Answer<?> result = createAnswer();
		try{
			deployUtils.clear(DeployType.Tuan);
			NewJedis redis = redisService.getJedis();
			//团购商户
			redisKeys(redis, DeployType.TuanShop);
			//团购
			redisKeys(redis, DeployType.Tuan);
		}catch(Exception exp){
			result.setCode(-1);
			result.setMsg(exp.getMessage());
			log.error(exp.getMessage(),exp);
		}
		return result;
	}
	@RequestMapping(value = "/undepActivity.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unDeployActivity(HttpServletRequest request, HttpServletResponse response) {
		Answer<?> result = createAnswer();
		try{
			NewJedis redis = redisService.getJedis();
			//活动商户
			redisKeys(redis, DeployType.ActivityShop);
			//活动
			redisKeys(redis, DeployType.Activity);
		}catch(Exception exp){
			result.setCode(-1);
			result.setMsg(exp.getMessage());
			log.error(exp.getMessage(),exp);
		}
		return result;
	}
	@RequestMapping(value = "/undepAndClearActivity.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unDeployAndClearActivity(HttpServletRequest request, HttpServletResponse response) {
		Answer<?> result = createAnswer();
		try{
			deployUtils.clear(DeployType.Activity);
			NewJedis redis = redisService.getJedis();
			//活动商户
			redisKeys(redis, DeployType.ActivityShop);
			//活动
			redisKeys(redis, DeployType.Activity);
		}catch(Exception exp){
			result.setCode(-1);
			result.setMsg(exp.getMessage());
			log.error(exp.getMessage(),exp);
		}
		return result;
	}
	
	@RequestMapping(value = "/undepCard.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unDeployCard(HttpServletRequest request, HttpServletResponse response) {
		Answer<?> result = createAnswer();
		try{
			NewJedis redis = redisService.getJedis();
			//卡
			redisKeys(redis, DeployType.Card);
		}catch(Exception exp){
			result.setCode(-1);
			result.setMsg(exp.getMessage());
			log.error(exp.getMessage(),exp);
		}
		return result;
	}
	@RequestMapping(value = "/undepAndClearCard.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unDeployAndClearCard(HttpServletRequest request, HttpServletResponse response) {
		Answer<?> result = createAnswer();
		try{
			deployUtils.clear(DeployType.Card);
			NewJedis redis = redisService.getJedis();
			//卡
			redisKeys(redis, DeployType.Card);
		}catch(Exception exp){
			result.setCode(-1);
			result.setMsg(exp.getMessage());
			log.error(exp.getMessage(),exp);
		}
		return result;
	}
	
	@RequestMapping(value = "/undepTicket.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unDeployTicket(HttpServletRequest request, HttpServletResponse response) {
		Answer<?> result = createAnswer();
		try{
			NewJedis redis = redisService.getJedis();
			redisKeys(redis, DeployType.Ticket);
		}catch(Exception exp){
			result.setCode(-1);
			result.setMsg(exp.getMessage());
			log.error(exp.getMessage(),exp);
		}
		return result;
	}

	@RequestMapping(value = "/undepAndClearTicket.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unDeployAndClearTicket(HttpServletRequest request, HttpServletResponse response) {
		Answer<?> result = createAnswer();
		try{
			deployUtils.clear(DeployType.Ticket);
			NewJedis redis = redisService.getJedis();
			redisKeys(redis, DeployType.Ticket);
		}catch(Exception exp){
			result.setCode(-1);
			result.setMsg(exp.getMessage());
			log.error(exp.getMessage(),exp);
		}
		return result;
	}

	@RequestMapping(value = "/undepShop.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unDeployShop(HttpServletRequest request, HttpServletResponse response) {
		Answer<?> result = createAnswer();
		try{
			NewJedis redis = redisService.getJedis();
			//商户，合并3个key为一个，删除其他两个
			redisKeys(redis, DeployType.Shop);
		}catch(Exception exp){
			result.setCode(-1);
			result.setMsg(exp.getMessage());
			log.error(exp.getMessage(),exp);
		}
		return result;
		
	}
	@RequestMapping(value = "/undepAndClearShop.htm", method = RequestMethod.POST)
	public @ResponseBody Answer<?> unDeployAndClearShop(HttpServletRequest request, HttpServletResponse response) {
		Answer<?> result = unDeployTuan(request, response);
		if(result.getCode()!=0){
			return result;
		}
		result = unDeployActivity(request, response);
		if(result.getCode()!=0){
			return result;
		}
		result = unDeployCard(request, response);
		if(result.getCode()!=0){
			return result;
		}
		result = unDeployTicket(request, response);
		if(result.getCode()!=0){
			return result;
		}
		try{
			deployUtils.clear(DeployType.Shop);
			NewJedis redis = redisService.getJedis();
			//商户，合并3个key为一个，删除其他两个
			redisKeys(redis, DeployType.Shop);
		}catch(Exception exp){
			result.setCode(-1);
			result.setMsg(exp.getMessage());
			log.error(exp.getMessage(),exp);
		}
		return result;
		
	}
	private void redisKeys(NewJedis redis,DeployType type){
		//商户，合并3个key为一个，删除其他两个
		redis.zunionstore("dep:"+type.getCode()+":que", "dep:"+type.getCode()+":que","dep:"+type.getCode()+":err","dep:"+type.getCode()+":time");
		redis.del("dep:"+type.getCode()+":err","dep:"+type.getCode()+":time");
	}
}